import includeJs from "@/utils/include-js";
import { mapState, mapGetters } from "vuex";
export default {
	data() {
		return {
			tplload: false
		}
	},
	computed: {
		...mapState('open', ['order_sn', 'customer']),
		...mapGetters('open', ['tpl', 'tplData', 'config', 'views', 'behaviorList']),
	},
	methods: {
		// 获取模板
		getTplInfo(id, type = 1) {
			// eslint-disable-next-line
			return new Promise(async (reslove, reject) => {
				const { query } = this.$route;
				let params = { ...query, id, type }
				this.tplload = true
				await this.$store.dispatch('open/adView', params).catch((e) => {
					this.$toast({
						message: e,
						position: "top"
					});
					reject(e)
					throw e;
				})
					.finally(() => {
						this.tplload = false;
					});

				this.behavior('monitor')
				setTimeout(() => {
					reslove()
				}, 300);
			})
		},
		// C端 -- 客服信息 - 获取
		async getCus(id, type = 1) {
			const { query } = this.$route;
			let params = { ...query, id, type }
			const data = await this.$store.dispatch('open/adCustomer', params)
			await this.adVisit(data);
		},
		// C端 -- 客服 - 点击数 - 提交
		async adVisit() {
			const { contact, contact_type, user_id, type, id } = this.customer;
			if (!id) return;
			const { id: templateId } = this.tpl;
			const { query } = this.$route;
			let params = {
				contact,
				contact_type,
				ad_customer_id: id,
				user_id,
				type,
				id: templateId,
				id_stage: query.id_stage || 0,
				id_supplier: query.id_supplier || 0,
				// ad_url:window.location.href,
				...query
			}
			if (query.tg_id) {
				params.id = query.tg_id
			}
			if (query.tg_type) {
				params.type = query.tg_type
			}
			await this.$api.adVisit(params);
		},
		// 客服 - 行为数 - 提交
		async adBehavior(behavior = 'copy') {
			const { contact, contact_type, id, user_id, type } = this.customer;
			const { id: templateId } = this.tpl;
			const { query } = this.$route;
			this.behavior(behavior);
			let params = {
				type,
				user_id,
				ad_customer_id: id,
				id: templateId,
				contact,
				contact_type,
				id_stage: query.id_stage || 0,
				id_supplier: query.id_supplier || 0,
				actionType: behavior,
				// ad_url:window.location.href,
				...query
			}
			if (query.tg_id) {
				params.id = query.tg_id
			}
			if (query.tg_type) {
				params.type = query.tg_type
			}
			await this.$api.adBehavior(params).catch(() => { });
		},
		behavior(type = 'copy', cb) {
			for (const item of this.behaviorList) {
				if (item.post_type != 'js_web') continue;
				if (type == 'monitor') {
					includeJs.source(item['behavior_' + type]);
					continue
				}
				if (item.behavior_monitor && item['behavior_' + type]) {
					includeJs.exec(item['behavior_' + type]);
				}
			}
			cb && cb()
		}
	}
}
